<template>
	<view class="container">
		<!-- 动作列表 -->
		<view class="action-list">
			<view class="action-item-wrapper" v-for="(item, index) in workoutList" :key="index">
				<!-- 动作卡片 -->
				<view class="action-card">
					<view class="card-header">
						<image class="action-image" :src="item.image || '/static/logo.png'" mode="aspectFill"></image>
						<view class="action-info">
							<text class="action-title">{{ item.name }}</text>
							<text class="action-desc">{{ item.sets }} 组 × {{ item.duration }} 秒</text>
						</view>
					</view>
				</view>
				
				<!-- 倒计时显示器 - 插入在当前动作卡片下方 -->
				<view class="countdown-section" v-if="currentActionIndex === index">
					<view class="current-action-info">
						<text class="current-action-name">{{ item.name }}</text>
						<text class="current-action-progress">第 {{ currentSetIndex + 1 }} / {{ item.sets }} 组</text>
					</view>
					<scroll-view class="time-scroll" scroll-x="true" show-scrollbar="false">
						<view class="time-list">
							<view 
								v-for="(setItem, setIndex) in getCurrentSetsList()" 
								:key="setIndex"
								class="time-item"
								:class="getSetClass(setIndex)"
							>
								<text class="time-text">{{ setItem.time }}</text>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		
		<!-- 空状态提示 -->
		<view class="empty-tip" v-if="workoutList.length === 0">
			<text class="tip-text">还没有动作数据</text>
		</view>
		
		<!-- 底部操作按钮 -->
		<view class="bottom-actions">
			<button class="btn-end" type="default" @click="endWorkout">
				<text class="btn-text">结束锻炼</text>
			</button>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				workoutList: [], // 训练动作列表
				currentActionIndex: 0, // 当前执行的动作索引
				currentSetIndex: 0, // 当前动作的第几组
				currentSetTime: 0, // 当前组的剩余时间
				setTimers: [], // 每个动作的每组倒计时数组
				timer: null, // 定时器
				innerAudioContext: null // 音频对象
			}
		},
		onLoad(options) {
			// 先清空所有数据，确保不会累积
			this.resetData();
			
			// 初始化音频对象
			this.initAudio();
			
			// 接收传递的动作列表数据
			if (options.workoutData) {
				try {
					const data = JSON.parse(decodeURIComponent(options.workoutData));
					this.workoutList = data;
					
					// 初始化倒计时数据
					this.initSetTimers();
					
					// 页面加载时开始倒计时
					this.startCountdown();
				} catch (e) {
					console.error('解析动作数据失败:', e);
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					});
				}
			}
		},
		onUnload() {
			// 页面卸载时清除定时器和数据
			this.clearTimer();
			this.resetData();
			// 销毁音频对象
			if (this.innerAudioContext) {
				this.innerAudioContext.destroy();
				this.innerAudioContext = null;
			}
		},
		methods: {
			// 初始化音频
			initAudio() {
				// 可能的音频文件路径列表
				const audioPaths = [
					'/static/audio/prompt.mp3',
					'/static/prompt.mp3',
					'../../static/audio/prompt.mp3',
					'../static/audio/prompt.mp3',
					'./static/audio/prompt.mp3',
					'/static/sounds/prompt.mp3'
				];
				
				let currentPathIndex = 0;
				
				const tryLoadAudio = () => {
					if (currentPathIndex >= audioPaths.length) {
						console.warn('所有音频路径都加载失败，将使用震动反馈');
						this.innerAudioContext = null;
						return;
					}
					
					try {
						if (this.innerAudioContext) {
							this.innerAudioContext.destroy();
						}
						
						this.innerAudioContext = uni.createInnerAudioContext();
						this.innerAudioContext.src = audioPaths[currentPathIndex];
						this.innerAudioContext.autoplay = false;
						
						// 配置音频属性以支持混音播放
						this.innerAudioContext.mixWithOther = true;  // 允许与其他音频混音
						this.innerAudioContext.obeyMuteSwitch = false;  // 不遵循静音开关，确保提示音能播放
						this.innerAudioContext.volume = 1.0;  // 设置音量为最大
						
						// 监听音频加载成功
						this.innerAudioContext.onCanplay(() => {
							console.log('音频加载成功:', audioPaths[currentPathIndex]);
						});
						
						// 监听音频加载错误（只在初始化时设置）
						this.innerAudioContext.onError((res) => {
							console.warn(`音频路径 ${audioPaths[currentPathIndex]} 加载失败:`, res);
							currentPathIndex++;
							setTimeout(tryLoadAudio, 100); // 延迟100ms后尝试下一个路径
						});
						
						// 监听播放结束事件
						this.innerAudioContext.onEnded(() => {
							// 播放结束后重置到开始位置，准备下次播放
							this.innerAudioContext.seek(0);
						});
						
					} catch (e) {
						console.warn('音频初始化失败:', e);
						currentPathIndex++;
						setTimeout(tryLoadAudio, 100);
					}
				};
				
				tryLoadAudio();
			},
			// 重置所有数据
			resetData() {
				this.workoutList = [];
				this.currentActionIndex = 0;
				this.currentSetIndex = 0;
				this.currentSetTime = 0;
				this.setTimers = [];
			},
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 初始化倒计时数据
			initSetTimers() {
				this.setTimers = this.workoutList.map(action => {
					const sets = [];
					for (let i = 0; i < action.sets; i++) {
						sets.push({
							time: action.duration,
							initialTime: action.duration
						});
					}
					return sets;
				});
				
				// 初始化第一个动作的第一组
				if (this.workoutList.length > 0) {
					this.currentSetTime = this.workoutList[0].duration;
				}
			},
			// 获取当前动作的组数列表
			getCurrentSetsList() {
				if (this.currentActionIndex >= 0 && this.currentActionIndex < this.setTimers.length) {
					return this.setTimers[this.currentActionIndex] || [];
				}
				return [];
			},
			// 获取组的样式类
			getSetClass(setIndex) {
				if (setIndex === this.currentSetIndex) {
					return 'active';
				} else if (setIndex < this.currentSetIndex) {
					return 'completed';
				}
				return '';
			},
			// 开始倒计时
			startCountdown() {
				this.timer = setInterval(() => {
					// 检查是否所有动作都完成
					if (this.currentActionIndex >= this.workoutList.length) {
						this.clearTimer();
						uni.showToast({
							title: '锻炼完成！',
							icon: 'success'
						});
						return;
					}
					
					// 当前组倒计时减1
					if (this.currentSetTime > 0) {
						this.currentSetTime--;
						// 更新setTimers中的时间
						this.setTimers[this.currentActionIndex][this.currentSetIndex].time = this.currentSetTime;
					} else {
						// 当前组完成，播放提示音或震动反馈
						this.playPrompt();
						
						// 切换到下一组
						this.currentSetIndex++;
						
						// 检查当前动作是否所有组都完成
						if (this.currentSetIndex >= this.workoutList[this.currentActionIndex].sets) {
							// 当前动作完成，切换到下一个动作
							this.currentActionIndex++;
							this.currentSetIndex = 0;
							
							// 检查是否还有下一个动作
							if (this.currentActionIndex < this.workoutList.length) {
								this.currentSetTime = this.workoutList[this.currentActionIndex].duration;
							}
						} else {
							// 开始当前动作的下一组
							this.currentSetTime = this.workoutList[this.currentActionIndex].duration;
						}
					}
				}, 1000);
			},
			// 播放提示音或震动反馈
			playPrompt() {
				if (this.innerAudioContext) {
					// 播放三次短促的提示音，增强可听性
					// 即使背景音乐很大，连续的"哔-哔"提示音也更容易被注意到
					this.playMultipleBeeps(2, 250); // 播放2次，间隔250ms
				}
			},
			// 播放多次提示音（哔-哔效果）
			playMultipleBeeps(count, interval) {
				let playCount = 0;
				
				const playOnce = () => {
					if (playCount >= count) {
						return;
					}
					
					try {
						// 停止当前播放
						this.innerAudioContext.stop();
						// 重置到开始位置
						this.innerAudioContext.seek(0);
						// 确保最大音量
						this.innerAudioContext.volume = 1.0;
						// 播放
						this.innerAudioContext.play();
						
						console.log(`播放第${playCount + 1}次提示音`);
						playCount++;
						
						// 如果还需要继续播放，设置延时
						if (playCount < count) {
							setTimeout(playOnce, interval);
						}
					} catch (e) {
						console.warn(`第${playCount + 1}次播放失败:`, e);
					}
				};
				
				// 开始第一次播放
				playOnce();
			},
			// 降级到震动反馈
			fallbackToVibrate() {
				uni.vibrateShort({
					success: () => {
						console.log('使用震动反馈');
					},
					fail: (err) => {
						console.warn('震动反馈也失败了:', err);
					}
				});
			},
			// 清除定时器
			clearTimer() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},
			// 结束锻炼
			endWorkout() {
				uni.showModal({
					title: '提示',
					content: '确定要结束当前锻炼吗？',
					success: (res) => {
						if (res.confirm) {
							// 清除定时器
							this.clearTimer();
							// 重置数据
							this.resetData();
							// 销毁音频对象
							if (this.innerAudioContext) {
								this.innerAudioContext.destroy();
								this.innerAudioContext = null;
							}
							// 返回上一页
							uni.navigateBack({
								delta: 1
							});
						}
					}
				});
			}
		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #F5F5F5;
		padding-bottom: 240rpx;
	}
	
	/* 动作列表 */
	.action-list {
		padding: 30rpx;
	}
	
	.action-card {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}
	
	.card-header {
		display: flex;
		align-items: center;
	}
	
	.action-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 16rpx;
		background-color: #F0F0F0;
		flex-shrink: 0;
	}
	
	.action-info {
		flex: 1;
		margin-left: 30rpx;
		display: flex;
		flex-direction: column;
	}
	
	.action-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333333;
		margin-bottom: 12rpx;
	}
	
	.action-desc {
		font-size: 26rpx;
		color: #999999;
		line-height: 1.5;
	}
	
	/* 倒计时选择器 */
	.countdown-section {
		padding: 0 30rpx 30rpx;
	}
	
	.current-action-info {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.current-action-name {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
	}
	
	.current-action-progress {
		font-size: 28rpx;
		color: #52C41A;
		font-weight: 500;
	}
	
	.time-scroll {
		width: 100%;
		white-space: nowrap;
	}
	
	.time-list {
		display: inline-flex;
		gap: 16rpx;
	}
	
	.time-item {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		min-width: 140rpx;
		height: 140rpx;
		border-radius: 20rpx;
		background-color: #FFFFFF;
		border: 3rpx solid #E0E0E0;
		flex-shrink: 0;
	}
	
	.time-item.active {
		background-color: #52C41A;
		border-color: #52C41A;
		box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);
	}
	
	.time-item.completed {
		background-color: #F5F5F5;
		border-color: #E0E0E0;
		opacity: 0.6;
	}
	
	.time-text {
		font-size: 56rpx;
		font-weight: bold;
		color: #AAAAAA;
	}
	
	.time-item.active .time-text {
		color: #FFFFFF;
	}
	
	.time-item.completed .time-text {
		color: #CCCCCC;
		text-decoration: line-through;
	}
	
	/* 空状态提示 */
	.empty-tip {
		padding: 60rpx 40rpx;
		text-align: center;
	}
	
	.tip-text {
		font-size: 28rpx;
		color: #AAAAAA;
	}
	
	/* 底部操作按钮 */
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #F5F5F5;
		padding: 30rpx;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
	}
	
	.btn-end {
		width: 100%;
		height: 96rpx;
		border-radius: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: 500;
		border: none;
		background-color: #FF4D4F;
		color: #FFFFFF;
	}
	
	.btn-end::after {
		border: none;
	}
	
	.btn-text {
		font-size: 32rpx;
	}
</style>
